import net from 'node:net'
import http from "node:http"
import { typeOfRequest } from '../http/mime.js'
import isFresh from '../http/isFresh.js'
import contentType from '../http/contentType.js'
import Accepts from '../http/Accepts.js'
import { IHttpApplication, IHttpContext, IHttpRequest } from "../types/index.d.ts"

export class HttpRequest implements IHttpRequest {

  _cachedURL?: URL
  _cachedQuery?: any
  _accept?: any
  IP?: string

  //
  [key: string]: any;

  constructor(
    public app: IHttpApplication,
    public ctx: IHttpContext,
    public req: http.IncomingMessage,
    public res: http.ServerResponse) {
  }

  /**
   * Return req headers
   */
  get headers(): http.IncomingHttpHeaders {
    return this.req.headers
  }

  /**
   * Set req headers
   */
  set headers(val: http.IncomingHttpHeaders) {
    this.req.headers = val
  }

  get method(): string {
    return this.req.method
  }

  set method(val: string) {
    this.req.method = val
  }

  /**
   * Return the protocol string "http" or "https"
   * when requested with TLS. When the proxy setting
   * is enabled the "X-Forwarded-Proto" header
   * field will be trusted. If you're running behind
   * a reverse proxy that supplies https for you this
   * may be enabled.
   */
  get protocol(): string {
    // if ((this.socket as tls.TLSSocket).encrypted) return 'https'
    if ((this.socket as any).encrypted) return 'https'
    if (!this.app.proxy) return 'http'
    const proto = this.get('X-Forwarded-Proto')
    return proto ? (proto as string).split(/\s*,\s*/, 1)[0] : 'http'
  }

  /**
   * Parse the "Host" header field host
   * and support X-Forwarded-Host when a
   * proxy is enabled.
   *
   * @return hostname:port
   */
  get host(): string {
    const proxy = this.app.proxy
    let host = proxy && this.get('X-Forwarded-Host')
    if (!host) {
      if (this.req.httpVersionMajor >= 2) host = this.get(':authority')
      if (!host) host = this.get('Host')
    }
    if (!host) return ''
    return (host as string).split(/\s*,\s*/, 1)[0]
  }

  /**
   * Parse the "Host" header field hostname
   * and support X-Forwarded-Host when a
   * proxy is enabled.
   */
  get hostname(): string {
    const host = this.host
    if (!host) return ''
    if (host[0] === '[') return this.URL.hostname || '' // IPv6
    return host.split(':', 1)[0]
  }

  // /**
  //  * Set request URL.
  //  */
  // set url(str) {
  //   this.req.url = str
  // }

  /**
   * Get origin of URL.
   */
  get origin(): string {
    return `${this.protocol}://${this.host}`
  }

  /**
   * Get request URL.
   */
  get url(): string {
    return this.req.url
  }

  /**
   * Get WHATWG parsed URL Lazily memoized.
   */
  get URL(): URL | any {
    if (!this._cachedURL) {
      try {
        this._cachedURL = new URL(`${this.origin}${this.req.url || ''}`)
      } catch (err) {
        this._cachedURL = Object.create(null)
      }
    }
    return this._cachedURL
  }

  /**
   * Get full request URL.
   *
   * @return {String}
   */
  get href() {
    // const originalUrl = this.req.url
    // if(/^https?:\/\//i.test(originalUrl)) return originalUrl
    // return this.origin + originalUrl
    return this.URL.href
  }

  /**
   * Get request pathname.
   *
   * @return {String}
   */
  get pathname() {
    return this.URL.pathname
  }

  // /**
  //  * Set pathname, retaining the query string when present.
  //  *
  //  * @param {String} str
  //  */
  // set pathname(str) {
  //   const url = parseUrl(this.req)
  //   if(url.pathname === str) return
  //
  //   url.pathname = str
  //   // TODO hash?
  //   this.url = `${url.pathname}${url?.search}`
  // }
  get search() {
    return this.URL.search
  }

  get searchParams(): URLSearchParams {
    return this.URL.searchParams
  }

  /**
   * /path/:module/:id
   * /path/user/123?a=1&b=2&a=3
   * => {a:[1,3], b:2}
   *
   * @return {object}
   */
  get query() {
    if (!this._cachedQuery) {
      const _cachedQuery = {}
      this.searchParams.forEach((value, key) => {
        const paramsValue = _cachedQuery[key]
        if (paramsValue == null) {
          _cachedQuery[key] = value
        } else if (Array.isArray(paramsValue)) {
          _cachedQuery[key].push(value)
        } else {
          _cachedQuery[key] = [paramsValue, value]
        }
      })
      this._cachedQuery = _cachedQuery
    }
    return this._cachedQuery
  }

  /**
   * Set query string as an object.
   */
  set query(queryObj: object) {
    this._cachedQuery = queryObj
  }

  /**
   * Check if the request is fresh, aka
   * Last-Modified and/or the ETag still match.
   */
  get fresh(): boolean {
    const method = this.method
    const s = this.ctx.status

    // GET or HEAD for weak freshness validation only
    if (method !== 'GET' && method !== 'HEAD') return false

    // 2xx or 304 as per rfc2616 14.26
    if ((s >= 200 && s < 300) || s === 304) {
      return isFresh(this.req.headers, this.res.getHeaders())
    }

    return false
  }

  /**
   * Check if the request is stale, aka
   * "Last-Modified" and / or the "ETag" for the
   * resource has changed.
   */
  get stale(): boolean {
    return !this.fresh
  }

  /**
   * Check if the request is idempotent.
   */
  get idempotent(): boolean {
    const methods = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE']
    return !!~methods.indexOf(this.method)
  }

  /**
   * Return the request socket.
   */
  get socket(): net.Socket {
    return this.req.socket
  }

  /**
   * Get the charset when present or undefined.
   */
  get charset(): string {
    try {
      const { parameters } = contentType.parse(this.req)
      return parameters.charset || ''
    } catch (e) {
      return ''
    }
  }

  /**
   * Return parsed Content-Length when present.
   */
  get length(): number {
    const len = this.get('Content-Length')
    if (len === '') return 0
    return ~~len
  }

  /**
   * Shorthand for:
   */
  get secure(): boolean {
    return this.protocol === 'https'
  }

  /**
   * When `app.proxy` is `true`, parse
   * the "X-Forwarded-For" ip address list.
   *
   * For example if the value was "client, proxy1, proxy2"
   * you would receive the array `["client", "proxy1", "proxy2"]`
   * where "proxy2" is the furthest down-stream.
   */
  get ips(): string[] {
    const proxy = this.app.proxy
    const val = this.get(this.app.proxyIpHeader)
    let ips = proxy && val
      ? val.split(/\s*,\s*/)
      : []
    if (this.app.maxIpsCount > 0) {
      ips = ips.slice(-this.app.maxIpsCount)
    }
    return ips
  }

  /**
   * Return request's remote address
   * When `app.proxy` is `true`, parse
   * the "X-Forwarded-For" ip address list and return the first one
   */
  get ip(): string {
    if (!this.IP) {
      this.IP = this.ips[0] || this.socket.remoteAddress || ''
    }
    return this.IP
  }

  /**
   * Set ip
   */
  set ip(val) {
    this.IP = val
  }

  /**
   * Return subdomains as an array.
   *
   * Subdomains are the dot-separated parts of the host before the main domain
   * of the app. By default, the domain of the app is assumed to be the last two
   * parts of the host. This can be changed by setting `app.subdomainOffset`.
   *
   * For example, if the domain is "tobi.ferrets.example.com":
   * If `app.subdomainOffset` is not set, this.subdomains is
   * `["ferrets", "tobi"]`.
   * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`.
   */
  get subdomains(): string[] {
    const offset = this.app.subdomainOffset
    const hostname = this.hostname
    if (net.isIP(hostname)) return []
    return hostname
      .split('.')
      .reverse()
      .slice(offset)
  }

  /**
   * Get accept object. Lazily memoized.
   */
  get accept(): any {
    return this._accept || (this._accept = Accepts(this.req))
  }

  /**
   * Set accept object.
   */
  set accept(obj: any) {
    this._accept = obj
  }

  /**
   * Check if the given `type(s)` is acceptable, returning
   * the best match when true, otherwise `false`, in which
   * case you should respond with 406 "Not Acceptable".
   *
   * The `type` value may be a single mime type string
   * such as "application/json", the extension name
   * such as "json" or an array `["json", "html", "text/plain"]`. When a list
   * or array is given the _best_ match, if any is returned.
   *
   * Examples:
   *
   *     // Accept: text/html
   *     this.accepts('html');
   *     // => "html"
   *
   *     // Accept: text/*, application/json
   *     this.accepts('html');
   *     // => "html"
   *     this.accepts('text/html');
   *     // => "text/html"
   *     this.accepts('json', 'text');
   *     // => "json"
   *     this.accepts('application/json');
   *     // => "application/json"
   *
   *     // Accept: text/*, application/json
   *     this.accepts('image/png');
   *     this.accepts('png');
   *     // => false
   *
   *     // Accept: text/*;q=.5, application/json
   *     this.accepts(['html', 'json']);
   *     this.accepts('html', 'json');
   *     // => "json"
   */
  accepts(...args: any[]): string | any[] | false {
    return this.accept.types(...args)
  }

  /**
   * Return accepted encodings or best fit based on `encodings`.
   *
   * Given `Accept-Encoding: gzip, deflate`
   * an array sorted by quality is returned:
   *
   *     ['gzip', 'deflate']
   */
  acceptsEncodings(...args: any[]): string | any[] {
    return this.accept.encodings(...args)
  }

  /**
   * Return accepted charsets or best fit based on `charsets`.
   *
   * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
   * an array sorted by quality is returned:
   *
   *     ['utf-8', 'utf-7', 'iso-8859-1']
   */
  acceptsCharsets(...args: any[]): string | any[] {
    return this.accept.charsets(...args)
  }

  /**
   * Return accepted languages or best fit based on `langs`.
   *
   * Given `Accept-Language: en;q=0.8, es, pt`
   * an array sorted by quality is returned:
   *
   *     ['es', 'pt', 'en']
   */
  acceptsLanguages(...args: any[]): any[] | string {
    return this.accept.languages(...args)
  }

  /**
   * Check if the incoming request contains the "Content-Type"
   * header field and if it contains any of the given mime `type`s.
   * If there is no request body, `null` is returned.
   * If there is no content type, `false` is returned.
   * Otherwise, it returns the first `type` that matches.
   *
   * Examples:
   *
   *     // With Content-Type: text/html; charset=utf-8
   *     this.is('html'); // => 'html'
   *     this.is('text/html'); // => 'text/html'
   *     this.is('text/*', 'application/json'); // => 'text/html'
   *
   *     // When Content-Type is application/json
   *     this.is('json', 'urlencoded'); // => 'json'
   *     this.is('application/json'); // => 'application/json'
   *     this.is('html', 'application/*'); // => 'application/json'
   *
   *     this.is('html'); // => false
   */
  is(type?: string | string[], ...types: string[]): string | false | null {
    return typeOfRequest(this.req, type, ...types)
  }

  /**
   * Return the request mime type void of
   * parameters such as "charset".
   */
  get type(): string {
    const type = this.get('Content-Type') as string
    if (!type) return ''
    return type.split(';')[0]
  }

  /**
   * Return request header.
   *
   * The `Referrer` header field is special-cased,
   * both `Referrer` and `Referer` are interchangeable.
   *
   * Examples:
   *
   *     this.get('Content-Type');
   *     // => "text/plain"
   *
   *     this.get('content-type');
   *     // => "text/plain"
   *
   *     this.get('Something');
   *     // => ''
   */
  get(field: string): string {
    const req = this.req
    switch (field = field.toLowerCase()) {
      case 'referer':
      case 'referrer':
        return (req.headers.referrer || req.headers.referer || '') as string
      default:
        return (req.headers[field] || '') as string
    }
  }

  /**
   * Inspect implementation.
   */
  inspect(): any {
    if (!this.req) return
    return this.toJSON()
  }

  /**
   * Return JSON representation.
   *
   * @return {Object}
   */
  toJSON(): { method: string, url: string, headers: http.IncomingHttpHeaders } {
    return {
      method: this.method,
      url: this.url,
      headers: this.headers
    }
  }
}
